package com.example.javabasic.thread.classtwo.threadlocal.demo4;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class BalkingData {
    private final String fileName;
    private String content;
    private boolean changed;
    public BalkingData(String fileName, String content) {
        this.fileName = fileName;
        this.content = content;
        this.changed = true;
    }


    public synchronized void change(String newContent){
        this.content = newContent;
        this.changed = true;
    }

    public synchronized void save() throws IOException {
        //如果没有变化直接返回  放弃操作
        if(!changed){
            return ;
        }
        doSave();
        this.changed = true;

    }

    //写文件
    public void doSave() throws IOException {
        System.out.println(Thread.currentThread().getName()+"保存了");
        try(Writer writer = new FileWriter(fileName,true)){
            writer.write(content);
            writer.write("\n");
            writer.flush();
        }

    }
}
